package com.gitee.dupe.log.config;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.gitee.dolt.log.event.OptLogDbHandler;
import com.gitee.dolt.model.RemoteData;
import com.gitee.dolt.utils.NumberUtils;
import com.gitee.dupe.log.entity.OptLog;
import com.gitee.dupe.log.service.IOptLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author LYH
 */
@Configuration
@RequiredArgsConstructor
public class OptLogConfiguration {

    private final IOptLogService optLogService;

    @Bean
    @ConditionalOnExpression("${dolt.log.enabled:true}")
    public OptLogDbHandler optLogDbHandler() {
        return optLogDTO -> {
            OptLog optLog = new OptLog().setRequestIp(optLogDTO.getRequestIp())
                    .setType(optLogDTO.getType())
                    .setUserId(new RemoteData<>(Convert.toLong(optLogDTO.getUserId())))
                    .setOptModule(optLogDTO.getOptModule()).setOptType(optLogDTO.getOptType())
                    .setOptDesc(optLogDTO.getOptDesc()).setClassPath(optLogDTO.getClassPath())
                    .setActionMethod(optLogDTO.getActionMethod()).setRequestUri(optLogDTO.getRequestUri())
                    .setHttpMethod(optLogDTO.getHttpMethod()).setParams(optLogDTO.getParams())
                    .setStartTime(optLogDTO.getStartTime()).setFinishTime(optLogDTO.getFinishTime())
                    .setConsumingTime(optLogDTO.getConsumingTime())
                    .setUa(optLogDTO.getUa()).setBizId(optLogDTO.getBizId());
            optLogService.save(handlerOptLog(optLog));
        };
    }


    private OptLog handlerOptLog(OptLog optLog) {
        String params = optLog.getParams();
        if (StrUtil.length(params) > NumberUtils.NUM_65535) {
            optLog.setParams(StrUtil.subSufByLength(params, NumberUtils.NUM_65535));
        }
        return optLog;
    }

}
